package com.baosight.xinreport.sql.read;

import cn.hutool.core.lang.Console;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.*;
import net.sf.jsqlparser.statement.select.*;

import java.util.ArrayList;
import java.util.List;

public class SqlReadTest {
    public static void main(String[] args) {
        String sql = "SELECT a.id, b.name FROM table1 a JOIN table2 b ON a.id = b.id";
        try {
            List<String> tables = new ArrayList<>();
            List<String> columns = new ArrayList<>();
            parseSql(sql, tables, columns);
            System.out.println("Data Tables:");
            for (String table : tables) {
                System.out.println(table);
            }
            System.out.println("Columns:");
            for (String column : columns) {
                System.out.println(column);
            }
        } catch (JSQLParserException e) {
            e.printStackTrace();
        }
    }

    public static void parseSql(String sql, List<String> tables, List<String> columns) throws JSQLParserException {
        Statement statement = CCJSqlParserUtil.parse(sql);
        if (statement instanceof Select) {
            Select select = (Select) statement;
            PlainSelect plainSelect = (PlainSelect) select.getSelectBody();
            // Get tables
            FromItem fromItem = plainSelect.getFromItem();


            if (fromItem instanceof Table) {
                tables.add(((Table) fromItem).getName());
            } else if (fromItem instanceof Join) {
//                Join join = (Join) fromItem;

            }
            List<Join> joins = plainSelect.getJoins();
            for (Join join : joins) {
                if (join instanceof Join ) {
                    String rightTableName = join.getRightItem().toString();
                    join.getRightItem().getClass();
                    if (join.getRightItem() instanceof Table) {
                        Table rightTable = (Table) join.getRightItem();
//                            rightTableName = rightTable.getAlias().getName();
                            rightTableName = rightTable.getName();
                    }
                    tables.add(rightTableName);
                }
            }
            // Get columns
            for (SelectItem item : plainSelect.getSelectItems()) {
                Console.log(item);
                if (item instanceof SelectExpressionItem) {
                    SelectExpressionItem expressionItem = (SelectExpressionItem) item;
                    columns.add(expressionItem.getExpression().toString());
                }
            }
        }
    }


}
